package com.minhua.jijiehao2.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * @author moo
 * @date 2017/11/7.
 * @describe 懒加载
 */

public abstract class BaseLazyFragment<V, P extends BaseMvpPresenter<V>> extends Fragment {
    protected P mPresenter;
    protected View mView;
    private boolean isPrepared;
    private boolean isFirstVisible = true;
    private boolean isFirstInvisible = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        int layoutId = getLayoutId();
        if (layoutId != 0) {
            mView = inflater.inflate(layoutId, container, false);
            return mView;
        } else {
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initPrepare();
    }

    private synchronized void initPrepare() {
        if (isPrepared) {
            onFirstUserVisible();
        } else {
            isPrepared = true;
        }
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter = getPresenter();
        mPresenter.attach((V) this);
        initView();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            if (isFirstVisible) {
                isFirstVisible = false;
                initPrepare();
            } else {
                onUserVisible();
            }
        } else {
            if (isFirstInvisible) {
                isFirstInvisible = false;
            } else {
                onUserInvisible();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detach();
        }
    }

    /**
     * 获取布局资源文件id
     *
     * @return 布局资源文件id
     */
    protected abstract int getLayoutId();

    /**
     * 获取presenter
     *
     * @return presenter
     */
    protected abstract P getPresenter();

    /**
     * 初始化View
     */
    protected abstract void initView();

    /**
     * 第一次用户可见
     * 加载数据，开启动画/广播...
     */
    protected abstract void onFirstUserVisible();

    /**
     * 用户可见
     * 开启动画/广播...
     */
    protected abstract void onUserVisible();

    /**
     * 用户不可见
     * 暂停动画，暂停广播...
     */
    protected abstract void onUserInvisible();

}
